﻿using System.Configuration;
using System.Web;
using System.Web.Configuration;
using Moq;
using NUnit.Framework;
using OpenWaves.ImageTransformations.Web;

namespace OpenWaves.ImageTransformations.UnitTests
{
    [TestFixture]
    public class WebImageTransformationModuleImplementationTests
    {
        [Test]
        public void When_RequestRawUrl_inludes_valid_ImageTransofmrationInfo_ModuleImplementation_rewrites_path_to_point_to_transformed_image()
        {
            const string rawUrl = "/image.jpg?t=ScaleToFill:100x100";

            var responseMock = new Mock<HttpResponseBase>();
            responseMock.SetupGet(r => r.Cache).Returns(new Mock<HttpCachePolicyBase>().Object);

            var httpContextMock = new Mock<HttpContextBase>();
            httpContextMock.SetupGet(c => c.Request).Returns(CreateHttpRequestMock(rawUrl));
            httpContextMock.SetupGet(c => c.Response).Returns(responseMock.Object);
            httpContextMock.Setup(c => c.RewritePath("/transformed/image.jpg"));

            var imageTransformationServiceMock = new Mock<IWebImageTransformationService>();
            imageTransformationServiceMock
                .Setup(s => s.GetTransformedImageUrl(Url.Parse("/image.jpg"), It.IsAny<IImageTransformation>()))
                .Returns(Url.ParseRelative("/transformed/image.jpg"));

            var moduleImplementation = new WebImageTransformationModuleImplementation(imageTransformationServiceMock.Object);

            moduleImplementation.PostAuthorizeRequest(httpContextMock.Object);
        }

        [Test]
        public void Test()
        {
            var module = new WebImageTransformationModuleImplementation(new Mock<IWebImageTransformationService>().Object);
            var urlBuilder = new RelativeUrlBuilder();

            module.EncodeTransformationInUrl(new ScaleToFillTransformation(123, 456).ToString(), urlBuilder);

            var t = module.DecodeTransformationFromUrl(urlBuilder.ToUrl(), new Mock<HttpContextBase>().Object);

            Assert.That(t, Is.InstanceOf<ScaleToFillTransformation>());
            Assert.That(((ScaleToFillTransformation)t).Width, Is.EqualTo(123));
            Assert.That(((ScaleToFillTransformation)t).Height, Is.EqualTo(456));
        }

        private static HttpRequestBase CreateHttpRequestMock(string rawUrl)
        {
            var httpRequestMock = new Mock<HttpRequestBase>();
            httpRequestMock.SetupGet(r => r.RawUrl).Returns(rawUrl);
            return httpRequestMock.Object;
        }
    }
}